package cn.stylefeng.guns.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BdUtil {
    public static class BdConfig{
        //测试号
//        public static String app_id = "23715947";
//        public static String client_id = "RXtXYMGFn8ny4wvhB6EVrUHm1owTXzyc";
//        public static String sk = "AvXpxz6s9Ask6pGAVOYtEd1E5Hju9fKr";
        //正式环境
        public static String app_id = "23842455";
        public static String client_id = "IUhjGTphLocwnVAE5oV1IkewheeOPvSi";
        public static String sk = "vMwFGanRTjp943zNsxD2rBbKfViSptak";

        public static String FIELD_SIGN = "sign";
    }

    /**
     * 获取用户的信息
     * @return
     */
    public static Map sessionKey(String code){
        String result = HttpClientUtil.doPostForm("https://spapi.baidu.com/oauth/jscode2sessionkey","code="+code+"&client_id="+BdConfig.client_id+"&sk="+BdConfig.sk);
        return JSON.parseObject(result, HashMap.class);
    }

    public static Map accessToken(){
        String result = HttpClientUtil.doGet("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id="+BdConfig.client_id+"&client_secret="+BdConfig.sk+"&scope=smartapp_snsapi_base");
        System.out.println("获取accessToken:"+result);
        return JSON.parseObject(result, HashMap.class);
    }

    public static class BdpayConfig{
        public static String appId = "43704";
        //字符
        public static String dealId = "1728496729";

        public static String appKey = "MMUd3E";

        public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKfB4bNVVrcYimAz" +
                "kqBXOXpvdzoRVr7EkYIJe0/2XoDEwPcQGBBOgTYs1EL2escZBEbYxSjPYXP9vQGO" +
                "SAhCTBqj4G+RaDNJUcq2GdsG3wsG6rz318s1S+xfRnF2mnFbzFwmYx+KWCsmDHuC" +
                "GpgP24GX3Tph78UH+QOAwEFcA+W9AgMBAAECgYAdZLhCLtK51B/yyTaIx5+3ly5B" +
                "y2XymQiRy02C7j0SvOa+o2BEAy1aq7IpZXyPxA9exn6NLwD5TN1AF4kBgXRJ8gk9" +
                "Bv5Rzb5k2kZbVYEIf+11eubcc7GbSJgyPB15UYv5R0xS0u9PDLiBm2kz71GctLyb" +
                "YpYd930JdOJ5pfs8lQJBANKdyqLdxFChu6zCL3ckJYVDM/qesrfrK6/DhU6GMkPp" +
                "n4iZQui+rsZl+4hCBumCDvAIjf/IZ7Lr/FENEt3y5+MCQQDL59zFzV0zrDuyywyn" +
                "dv1Lezpq7F/t2VcqGC721qlHQOjoe1Fmik3Yg97LH1Hj/aQvR/O4JvNyAq9Zs/jp" +
                "Ay3fAkEAtOzLp8Dt5X4p5Cwj7irk+GdUfZRaXlfs/V3uZBgvkdtdKlDOA3XaWaA9" +
                "xT1DBtCs2FHg+btEKZVC+LVMYdFKlQJADhtOZMjeZ9LElowBphxPTceKtRcBU/0z" +
                "UJA3v4/+ShWth1fwu71ZwV7uLPNPwQwtLbA2pkjbksmow/X1hHlZ1QJAJmVHsWdA" +
                "Ny8RN+YGNffaUY5WLzs/7pzP42jR9kAgGDH0FLpuw9FcrI3d6VgQ+OPLdg249rQ1" +
                "NgUQBeVS29jgow==";
        public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHlDBMTcJDmtVacR3sWbu2mNoGeE1qqXHdEmuGz2p5CcIPYGWyli48AyM6JAswi7uidCeHBr2WTPmusuyfg0eQ0XRj3Y9Ukx0RwNvnLg3THh5sBaC3ZKDt0TvhxmRZzUURjJAFtSqHKyhyb9tI9LL+ryEUhraut8TkRdnrfFtlvwIDAQAB";
    }

    public static Map<String,Object> createPay(String tpOrderId,String totalAmount,String dealTitle) throws Exception {
        Map<String,Object> result = new HashMap<>();
        result.put("dealId",BdpayConfig.dealId);
        result.put("appKey",BdpayConfig.appKey);
        result.put("totalAmount",totalAmount);
        result.put("tpOrderId",tpOrderId);
        result.put("dealTitle",dealTitle);
        result.put("signFieldsRange",1);
        Map<String,Object> bizInfo = new HashMap<>();
        bizInfo.put("tpData",result);
        result.put("bizInfo",JSON.toJSONString(bizInfo));
        Map<String,Object> sign = new HashMap<>();
        sign.put("appKey",result.get("appKey"));
        sign.put("dealId",result.get("dealId"));
        sign.put("totalAmount",result.get("totalAmount"));
        sign.put("tpOrderId",result.get("tpOrderId"));
        result.put("rsaSign",BdPayRSASignUtil.sign(sign,BdpayConfig.privateKey));
        return result;
    }

    /**
     * 将request中的参数转换成Map
     *
     * @param request
     * @return
     */
    public static Map<String, Object> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;
            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

    public static Map<String,Object> canselOrder(String orderId,String userId){
        Map<String,Object> req = new HashMap<>();
        req.put("orderId",orderId);
        req.put("userId",userId);
        req.put("method","nuomi.cashier.syncorderstatus");
        req.put("type",3);
        req.put("appKey", BdpayConfig.appKey);
        try{
            req.put("rsaSign", BdPayRSASignUtil.sign(req,BdpayConfig.privateKey));
        }catch (Exception e){
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();
        try{
            for (Map.Entry<String,Object> item : req.entrySet()){
                if(sb.length() == 0){
                    sb.append(item.getKey()+"="+URLEncoder.encode(item.getValue().toString(),"utf-8"));
                }else {
                    sb.append("&"+item.getKey()+"="+URLEncoder.encode(item.getValue().toString(),"utf-8"));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        String result = HttpClientUtil.doGet("https://etrade-api.baidu.com/cashier/syncOrderStatus?"+sb.toString());
        System.out.println("退款核销返回:"+result);
        Map<String,Object> resp = new HashMap<>();
        return resp;
    }

    public static Map<String,Object> orderRefund(String userId,String tpOrderId,String orderId,String bizRefundBatchId){
        Map<String,String> accessToken = accessToken();
        Map<String,Object> req = new HashMap<>();
        if(!accessToken.containsKey("access_token")){
            req.put("errno","1");
            req.put("msg","获取accesstoken失败"+accessToken.get("error"));
            return req;
        }

        req.put("access_token",accessToken.get("access_token"));
        req.put("bizRefundBatchId",bizRefundBatchId);
        req.put("orderId",orderId);
        req.put("isSkipAudit",1);
        req.put("refundReason",1);
        req.put("refundType",2);
        req.put("tpOrderId",tpOrderId);
        req.put("userId",userId);
        req.put("pmAppKey",BdpayConfig.appKey);

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String,Object> item : req.entrySet()){
            if(sb.length() == 0){
                sb.append(item.getKey()+"="+item.getValue());
            }else {
                sb.append("&"+item.getKey()+"="+item.getValue());
            }
        }
        String result = HttpClientUtil.doPostForm("https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/applyOrderRefund",sb.toString());
        System.out.println("退款返回:"+result);
        return JSON.parseObject(result, HashMap.class);
    }
}
